package com.example.demomcp;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Scanner;
import javax.imageio.ImageIO;

public class CS {
  public static   String chromePath = "C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe";

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean running = true;

        while (running) {
            System.out.println("请输入命令（打开谷歌浏览器/搜索 <关键词>/截屏/退出）：");
            String input = scanner.nextLine();

            if (input.equalsIgnoreCase("打开谷歌浏览器")) {
                openGoogleChrome();
            } else if (input.startsWith("搜索 ")) {
                String query = input.substring(3).trim();
                searchInChrome(query);
            } else if (input.equalsIgnoreCase("截屏")) {
                takeScreenshot();
            } else if (input.equalsIgnoreCase("退出")) {
                running = false;
                System.out.println("退出程序。");
            } else {
                System.out.println("未知命令，请重试。");
            }
        }

        scanner.close();
    }

    private static void openGoogleChrome() {
        try {
            // 指定 Google Chrome 的安装路径
//            String chromePath = "C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"; // Windows 示例路径
            // 对于 macOS 或 Linux，路径会有所不同，例如 "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"

            ProcessBuilder processBuilder = new ProcessBuilder(chromePath);
            processBuilder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void searchInChrome(String query) {
        try {
//            String chromePath = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"; // Windows 示例路径
            String searchUrl = "https://www.google.com/search?q=" + URLEncoder.encode(query, "UTF-8");
            ProcessBuilder processBuilder = new ProcessBuilder(chromePath, searchUrl);
            processBuilder.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // 可能需要导入 java.net.URLEncoder 并处理编码异常
            e.printStackTrace();
        }
    }

    private static void takeScreenshot() {
        try {
            Robot robot = new Robot();
            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage screenFullImage = robot.createScreenCapture(screenRect);

            // 保存截图到文件
            File screenshotFile = new File("screenshot.png");
            ImageIO.write(screenFullImage, "png", screenshotFile);

            System.out.println("截图已保存为: " + screenshotFile.getAbsolutePath());

        } catch (AWTException | IOException ex) {
            System.err.println(ex);
        }
    }

}
